﻿using DryIoc;
using Example;
using HandyControl.Controls;
using log4net;
using log4net.Config;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Server.ViewModels;
using PlaceOrder_Server.Views;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System.Configuration;
using System.Data;
using System.IO;
using System.Reflection;
using System.Windows;
using Application = System.Windows.Application;
using MessageBox = HandyControl.Controls.MessageBox;
using Window = System.Windows.Window;

namespace PlaceOrder_Server
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    //public partial class App : PrismApplication
    //{
    //    private static readonly ILog log = LogManager.GetLogger(typeof(App));
    //    private static Mutex mutex;

    //    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    //    {
    //        var logRepository = LogManager.GetRepository(System.Reflection.Assembly.GetEntryAssembly());
    //        XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

    //        // Register log4net logger
    //        containerRegistry.RegisterInstance(LogManager.GetLogger(typeof(App)));

    //        containerRegistry.Register<ILoginService, LoginService>();
    //        containerRegistry.RegisterDialog<LoginView, LoginViewModel>();
    //    }

//    protected override Window CreateShell()
//    {
//        return ContainerLocator.Container.Resolve<MainWindow>();
//    }

//    protected override void OnInitialized()
//    {
//        var dialog = ContainerLocator.Container.Resolve<IDialogService>();
//        dialog.ShowDialog("LoginView", callback =>
//        {
//            if (callback.Result != ButtonResult.OK)
//            {
//                Environment.Exit(0);
//                return;
//            }

//            var service = App.Current.MainWindow.DataContext as IConfigureService;
//            if (service != null)
//                service.Configure();
//            base.OnInitialized();
//        });
//    }


//    protected override void OnStartup(StartupEventArgs e)
//    {
//        bool isOwned;
//        string mutexName = "Global\\QuanYiPlaceOrderServer";

//        mutex = new Mutex(true, mutexName, out isOwned);

//        if (!isOwned)
//        {
//            log.Warn("Another instance of the application is already running.");
//            MessageBox.Show("Another instance of the application is already running.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
//            Application.Current.Shutdown();
//            return;
//        }

//        base.OnStartup(e);

//        var logger = ContainerLocator.Container.Resolve<ILog>();
//        logger.Info("Application started");
//    }

//    protected override void OnExit(ExitEventArgs e)
//    {
//        var logger = ContainerLocator.Container.Resolve<ILog>();
//        logger.Info("Application exited");

//        mutex?.ReleaseMutex();
//        base.OnExit(e);
//    }
//}
public partial class App : PrismApplication
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(App));
        private static Mutex mutex;

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterInstance(log); // 确保正确注册 log
            containerRegistry.Register<MainWindow>(); // 如果需要注册视图的话
            containerRegistry.Register<MainWindowViewModel>();

            //导航
            containerRegistry.RegisterForNavigation<IndexServerView, IndexServerViewModel>();
            //containerRegistry.RegisterForNavigation<TestView, TestViewModel>();
            //// Register other types
            containerRegistry.Register<ILoginService, LoginService>();
            containerRegistry.RegisterSingleton<IndexServerViewModel>();

            containerRegistry.RegisterSingleton<IUserHelper, UserHelper>();
            containerRegistry.RegisterSingleton<IDataHelper, DataHelper>();
            containerRegistry.RegisterSingleton<IDatabase, Database>();
            containerRegistry.RegisterSingleton<IDailyData, DailyData>();
            containerRegistry.RegisterSingleton<IData, Data>();
            containerRegistry.RegisterDialog<LoginView, LoginViewModel>();
        }

        protected override Window CreateShell()
        {
            //抑制时间报错
            AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
            AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
            return ContainerLocator.Container.Resolve<MainWindow>();
        }

        protected override void OnInitialized()
        {

            //var dialog = ContainerLocator.Container.Resolve<IDialogService>();
            //dialog.ShowDialog("LoginView", callback =>
            //{
            //    if (callback.Result != ButtonResult.OK)
            //    {
            //        Environment.Exit(0);
            //        return;
            //    }

            //    if (App.Current.MainWindow.DataContext is IConfigureService service)
            //    {
            //        service.Configure();
            //    }
            //    base.OnInitialized();
            //});
            base.OnInitialized();
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            // Ensure the log directory exists
            string logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
            }

            // Configure log4net
            log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));
            


            bool isOwned;
            string mutexName = "Global\\QuanYiPlaceOrderServer";

            mutex = new Mutex(true, mutexName, out isOwned);

            if (!isOwned)
            {
                log.Warn("Another instance of the application is already running.");
                Growl.ErrorGlobal("已开启服务端,请关闭");
                Application.Current.Shutdown();
                return;
            }

            AppLog.WriteInfo("程序启动");
            base.OnStartup(e);

        }

        protected override void OnExit(ExitEventArgs e)
        {
            log.Info("Application exited");

            mutex?.ReleaseMutex();
            base.OnExit(e);
        }
    }
}

